﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace IanUtil.DB
{
    public class IU_DB_SQLServer : IU_DB_DataBase
    {
        public override object GetConnection()
        {
            if (Connection == null)
            {
                Connection = new SqlConnection(ConnectionString);
            }
            if(((SqlConnection)Connection).State==ConnectionState.Closed)
            {
                ((SqlConnection)Connection).Open();
            }

            return Connection;
        }

        public override object SQLForScalar(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, (SqlConnection)GetConnection());
            object obj = cmd.ExecuteScalar();
            return obj;
        }

        public override void Dispose()
        {
            try
            {
                if (((SqlConnection)Connection).State != ConnectionState.Closed)
                {
                    ((SqlConnection)Connection).Close();
                }
            }
            catch (Exception)
            {
            }
        }

        public override DataSet SQLForDataSet(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, (SqlConnection)GetConnection());
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adapter.Fill(ds);
            return ds;
        }

        public override int ExcuteSQL(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, (SqlConnection)GetConnection());
            int effectRow = cmd.ExecuteNonQuery();
            return effectRow;
        }
    }
}
